#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time: 20-7-15 下午5:13
# @Author: HuangChuQin
# @Desc: 查询当前A股市场的所有股票，并保存到stock_base_info.stock_basic数据库
# @File: stock_info_write.py
# @Software: PyCharm

import baostock as bs
import common.util_mysql
import common.utils
import sys

# 配置文件
profile = 'profile.ini'
# 日志对象
logger = None
# 配置对象
config = None

# 数据库参数
db_param = {}
# 数据库连接
db_conn = None
# 操作sql
db_sql_dict = {}


def my_init_conf():
    global profile
    global logger
    global config
    global db_param

    # init confFile
    print("init config file:\t" + profile)
    config = common.utils.init_config(profile)
    if config is None:
        print("init config err, exit")
        sys.exit()
    print("init profile success")

    # init log
    log_config_file = config.get("COMMON", "LOG_CONFIG_PATH")
    log_config_name = config.get("COMMON", "LOG_NAME")
    print("log config : ", log_config_file, log_config_name)
    logger = common.utils.init_logger(log_config_file, log_config_name)
    if logger is None:
        print("init logger err, exit")
        sys.exit()
    print("init logger success")

    # init mysql
    db_param['SERVER'] = config.get("MYSQL", "SERVER")
    db_param['USER'] = config.get("MYSQL", "USER")
    db_param['PWD'] = config.get("MYSQL", "PWD")
    db_param['DBNAME'] = config.get("MYSQL", "DBNAME")


def db_conn_create():
    global db_conn
    db_conn = common.util_mysql.db_connect(db_param)
    if db_conn is None:
        logger.error('ConnDbMysql err')
        sys.exit()
    logger.info('connect mysql ok')


def db_conn_destroy():
    common.util_mysql.db_disconnect(db_conn)
    logger.info("destroy db_conn ok")


def get_stock_info():

    lg = bs.login()

    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    rs = bs.query_stock_basic()

    print('query_all_stock respond error_code:' + rs.error_code)
    print('query_all_stock respond  error_msg:' + rs.error_msg)

    return rs.error_code, rs.error_msg, rs.data


def replace_stock_info(stock_list):
    cursor = db_conn.cursor()
    for stock in stock_list:
        if stock[3] is '':
            cursor.execute(
                'replace into stock_basic (stock_code,stock_name,ipo_date,stock_type,stock_status) values (%s,%s,%s,%s,%s)',
                (stock[0], stock[1], stock[2], stock[4], stock[5])
            )
        else:
            cursor.execute(
                'replace into stock_basic (stock_code,stock_name,ipo_date,out_date,stock_type,stock_status) values (%s,%s,%s,%s,%s,%s)',
                (stock[0], stock[1], stock[2], stock[3], stock[4], stock[5])
            )
    cursor.close()


def main():
    error_code, error_msg, stock_list = get_stock_info()
    if error_code is "0":
        replace_stock_info(stock_list)
    else:
        logger.info("get_stock_info err, error_code:%s, error_msg:%s" % (error_code, error_msg))


if __name__ == "__main__":
    my_init_conf()
    db_conn_create()

    main()

    db_conn_destroy()

    # 退出程序
    logger.info("run end, exit")
